package com.tf.pemporaryfood.controller;

import com.tf.pemporaryfood.domain.VO.UserVO;
import com.tf.pemporaryfood.domain.entity.User;
import com.tf.pemporaryfood.service.UserService;
import com.tf.pemporaryfood.util.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *   用户controller
 * @author Young genius
 * @date 2021年05月28日 17:57
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 注册接口
     * http://127.0.0.1:8080/user/registered?userPhone=123456789&userName=ls&userPassword=123&userRole=1
     * @param userVO
     * @return
     */
    @RequestMapping(value = "/registered")
    public ApiResult<Void> registered(UserVO userVO){
        if (userService.addUser(userVO) == 1){
            return ApiResult.ok("注册成功");
        }else {
            return ApiResult.error(10001,"注册失败");
        }
    }

    /**
     * 登录
     * http://127.0.0.1:8080/user/login?userPhone=17630210387&userPassword=123
     * @param userVO userName用户名 userPassword密码
     * @return
     * 登录成功
     *{
     *  "data":{
     *      "userPhone":"17630210387",
     *      "userIcon":"17630210387",
     *      "userName":"wfb",
     *      "userRole":1,
     *      "userId":595957088316817408
     *      },
     *   "code":200,
     *   "message":"登录成功"
     *}
     * 登录失败
     * {
     *  "data":null,
     *  "code":10001,
     *  "message":"登录失败"
     * }
     */
    @RequestMapping("/login")
    public ApiResult<Void> logIn(UserVO userVO){
        ApiResult apiResult=new ApiResult();
        //查询数据库
        User user=userService.findUserByPhoneAndPassword(userVO.getUserPhone(), userVO.getUserPassword());
        Map<String,Object> loginRrsult=new HashMap<>();
        if (user!=null){
            //将需要返回给客户端的数据储存
            loginRrsult.put("userId", user.getUserId());
            loginRrsult.put("userName", user.getUserName());
            loginRrsult.put("userPhone", user.getUserPhone());
            loginRrsult.put("userRole", user.getUserRole());
            loginRrsult.put("userIcon", user.getUserIcon());
            apiResult.setData(loginRrsult);
            apiResult.setCode(200);
            apiResult.setMessage("登录成功");
            return apiResult;
        }else {
            return ApiResult.error(10001,"登录失败");
        }
    }
}
